package servlet;

import dao.EmployeeDao;
import dao.impl.EmployeeDaoImpl;
import entity.Employee;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/employee")
public class EmployeeServlet extends HttpServlet {

    private EmployeeDao employeeDao;

    public EmployeeServlet() {
        this.employeeDao = new EmployeeDaoImpl();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //若用户是已登录过的，则将请求转发到/WEB-INF/employ/employee.jsp资源中
        HttpSession session = req.getSession(false);
        if (session == null) {
            //肯定没有登录
            System.out.println("此客户肯定没有登录过，因为session为空");
            resp.sendRedirect(getServletContext().getContextPath()+"/login.jsp");
        } else {
            //进一步判断是否存在LOGIN_USER_KEY
            if (session.getAttribute("LOGIN_USER_KEY") == null) {
                //说明，虽然存在session，但用户没有登录
                System.out.println("虽然有Session，但是没有登录过");
                resp.sendRedirect(getServletContext().getContextPath()+"/login.jsp");
            } else {
                //查询出所有的图书
                List<Employee> all = employeeDao.findAll();
                //绑定到request范围
                req.setAttribute("ALL_Employee",all);
                System.out.println(all);
                //如果用户是已经登陆过的，则把请求转发/WEB-INF/employ/employee.jsp资源中
                req.getRequestDispatcher("/WEB-INF/employ/employee.jsp").forward(req,resp);
            }
        }
    }
}